<template>
    <view>
        <view class="p_20">
            <view class="dis_f_r_c m_b_10">
                <view class="release dis_f_c_c" @click="handleSend">发布</view>
            </view>
            <view class="content_box">
                <u--textarea v-model="query.bt"  autoHeight  border="none" placeholder="请输入标题" ></u--textarea>
                <u--textarea v-model="query.nr" border="none" placeholder="请输入内容..." ></u--textarea>
                <view @click="handleUploadClick">
                    <u-upload
                        :fileList="fileList1"
                        @afterRead="afterRead"
                        @delete="deletePic"
                        accept="media"
                        capture="album"
                        name="1"
                        multiple
                        :maxCount="9"
                        :max-size="20 * 1024 * 1024"
                        @oversize="oversize"
                    ></u-upload>
                </view>
                <view style="font-size: 24rpx;color: #666666">上传大小不超过20M</view>
                <view class="m_t_10">
                    <!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
                    <u--form
                        labelPosition="left"
                        :model="query"
                        :rules="rules"
                        ref="uForm"
                        labelWidth="100"
                    >
                        <u-form-item
                            label="联系人"
                            prop="lxrXm"
                            borderBottom
                            ref="item1"
                        >
                            <u--input
                                v-model="query.lxrXm"
                                border="none"
                                placeholder="请输入联系人"
                            ></u--input>
                        </u-form-item>
                        <u-form-item
                            label="联系电话"
                            prop="lxrDh"
                            borderBottom
                            ref="item1"
                        >
                            <u--input
                                v-model="query.lxrDh"
                                border="none"
                                placeholder="请输入联系电话"
                                type="number"
                                maxlength="11"
                            ></u--input>
                        </u-form-item>
                      <u-form-item
                          label="信息分类"
                          prop="lxNameEj"
                          borderBottom
                          ref="item1"
                      >
                        <uni-data-picker v-model="query.lxNameEj"  :localdata="pickerTypeList" placeholder="请选择分类" popup-title="请选择分类" @change="onTypeChange" ></uni-data-picker>
                      </u-form-item>
                        <u-form-item
                            label="地址"
                            prop="quantity"
                            borderBottom
                            ref="item1"
                        >
                            <uni-data-picker v-model="query.districts" :localdata="areaList" placeholder="请选择地区" popup-title="请选择地区" @change="onchange"  ></uni-data-picker>
                        </u-form-item>
                        <view class="dis_f_r_c m_t_10 m_b_10 f_s_14 c_9">{{query.dz}}</view>
                    </u--form>
                </view>
                <view class="dis_f_r_c m_t_10">
                    <u-checkbox-group
                        size="16"
                        v-model="checkboxValue"
                        placement="column"
                    >
                        <u-checkbox
                            activeColor="#54B62D"
                            label=" "
                            name="agreement"
                        >
                        </u-checkbox>
                    </u-checkbox-group>
                    <view class="f_s_14 c_blue" @click="handleToProtocol">《免责协议》 </view>
                </view>
                <view>
                    <u-divider text="发布规则"></u-divider>
                    <view class="" v-html="sendAsk"></view>
                </view>
            </view>
            <u-picker :show="showPicker"
                      :columns="columnsPicker"
                      :keyName="keyName"
                      @cancel="showPicker = false"
                      @confirm="handlePickerShure"></u-picker>
        </view>
        <!-- 授权弹窗 -->
        <s-auth-modal />
    </view>
</template>
<script>

import {baseUrl} from "@/sheep/request/baseUrl";
import {getByKeyApi, addInformationApi, getAddressApi, getAreaListApi} from "@/sheep/api";
export default {
    name: "index",
    data() {
        return {
            checkboxValue: [],
            pickerTypeList:[],
            sendAsk:'',
            columnsPicker:[],
            showPicker: false,
            keyName:'',
            fileListImg: [],
            unitList: [
                [{
                    label:'吨',
                    value:'吨'
                },       {
                    label:'方',
                    value:'方'
                }]
            ],
            fileList1: [],
            className: null,
            isRecharge: false,
            payNum: null,
            formData: {
                user: 'test'
            },
            areaList:[],
            query: {
                bt: '',
                nr: '',
                province: '',
                city: '',
                districts: '',
                lxrXm: '',
                lxrDh: '',
                sf: '',
                sfnm: '1',
                // lot:'',
                // lat:'',
            },
            rules: {
                'bt': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'nr': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'lxrXm': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'lxrDh': {
                    type: 'string',
                    required: true,
                    message: '请输入',
                    trigger: ['blur', 'change']
                },
                'lxNameEj': {
                    type: 'string',
                    required: true,
                    message: '请选择',
                    trigger: ['blur', 'change']
                },
                'sf': {
                    type: 'string',
                    required: true,
                    message: '请选择',
                    trigger: ['blur', 'change']
                },
            },

            isShow: false,
            classList:[],
            queryData:'',
            listId:'',
            queryName:'',
            vipRules:'',
        }
    },
    onLoad(params) {
    },
    onShow() {
        if (!this.isShow) {
            // this.handleReset()
        }
        this.getSendAsk()
        this.getClassList()
        this.getArea()
        this.getTypeList()
        // this.getImg()
        // this.isRecharge = false
        // this.getTagAllList()
        // this.getClassData()
    },
    methods: {
        handleToProtocol(e){
            uni.navigateTo({
                url: '/pages/agreement/index?type=1'
            })
        },
        async getSendAsk() {
            let res = await getByKeyApi("fbyq");
            this.sendAsk = res.data[0]?.configValue;
        },
        async getClassList() {
            let res = await getByKeyApi("cpfl");
            this.classList = [res.data]||[]
        },
        async getTypeList() {
            let res = await getByKeyApi("goods_type");
            this.pickerTypeList = res.data.map(item=>{
                let children=[]
                if (item.remark){
                    let s1 = item.remark.split('-')
                    children=s1.map(sItem=>{
                        return {
                            text: sItem,
                            value: sItem
                        }
                    })
                }
                return {
                    text: item.configName,
                    value: item.configName,
                    children:children
                }
            })
        },
        onchange(e) {
            console.log("e", e.detail.value);
            const value = e.detail.value
            if (value.length>0){
                this.query.province= value[0].text
                this.query.city= value[1].text
                this.query.districts= value[2].text
            }else{
                this.query.province = ''
                this.query.city = ''
                this.query.districts = ''
            }
        },
        getArea(){
            getAreaListApi().then(res=>{
                this.areaList = res.data
            })
        },
        onTypeChange(e){
            const value = e.detail.value
            console.log("value", value);
            if (value.length>0){
                this.query.lxNameYj = value[0].text
                this.query.lxNameEj = value[1].text
            }else{
                this.query.lxNameYj = ''
                this.query.lxNameEj = ''
            }

        },
        // 文件超出大小限制
        oversize() {
            uni.showToast({
                title: "上传最大不能超过20M",
                icon: 'none'
            })
        },

        // 选择收货地址
        handleMap() {
            let that = this;
            uni.showLoading({ title: "获取位置中" });
            uni.getLocation({
                type: "gcj02", //返回可以用于uni.openLocation的经纬度
                success: function (res) {
                    const latitude = res.latitude;
                    const longitude = res.longitude;
                    getAddressApi({ location: latitude + "," + longitude }).then((res) => {
                            that.query.dz = res.data;
                            that.query.lot = longitude;
                            that.query.lat = latitude;
                            uni.hideLoading();
                        }
                    );
                },
                fail: function (err) {
                    uni.hideLoading();
                    uni.showToast({
                        title: "获取位置失败",
                        icon: "none"
                    });
                }
            });
        },
        handleShowPicker(queryName,queryData,listId,list,keyName){
            /**
             * queryName 双向绑定的name,queryData 传给后端的字段名，listId picker的id,list picker的列表，keyName picker的keyName
             * */
            this.queryData = queryData
            this.queryName = queryName
            this.listId = listId
            this.columnsPicker = this[list]
            this.keyName = keyName
            this.showPicker = true
        },
        handlePickerShure(e){
            this.query[this.queryData] =  e.value[0][this.listId]
            this.query[this.queryName] =  e.value[0][this.keyName]
            this.showPicker = false
        },
        handleReset() {
            this.query = {
                productType:this.type,
                advertTitle: '',
                productImg: '',
                className: '',
                classId: '',
                lxNameEj: '',
                quantity: '',
                unit: '',
                price: '',
                priceType: '',
                receiveAddress: '',
                address: '',
                receiveTime: '',
            }
            this.fileList1 = []
            this.fileList2 = []
            //刷新页面
            console.log("88888888", this.query);
        },

        confirm(e) {
            this.query.receiveAddress = e.value[0].name + e.value[1].name + e.value[2].name
            this.showAddress = false
        },

        handleSend() {
            if (this.checkboxValue.length==0){
                uni.showToast({
                    title: '请勾选协议',
                    icon: 'none'
                })
                return
            }
            if (!this.query.bt){
                uni.showToast({
                    title: '请输入产品名称',
                    icon: 'none'
                })
                return
            }
            if (!this.query.nr){
                uni.showToast({
                    title: '请输入内容',
                    icon: 'none'
                })
                return
            }
            if (this.fileList1.length==0){
                uni.showToast({
                    title: '请上传图片',
                    icon: 'none'
                })
                return
            }
            if (!this.query.districts){
                uni.showToast({
                    title: '请选择地区',
                    icon: 'none'
                })
                return
            }
            this.$refs.uForm.validate().then(res=>{
                if (Array.isArray(this.fileList1)) {
                    if (this.fileList1.length > 0) {
                        this.fileList1.forEach((item, index) => {
                            if (index === 0) {
                                this.query.photo = item.ossId;
                            } else {
                                this.query.photo = this.query.photo + "," + item.ossId;
                            }
                        });
                    } else {
                        this.query.photo = "";
                    }
                }
                uni.showLoading({});
                addInformationApi(this.query).then(res => {
                    uni.hideLoading()
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                    if (res.code == 200){
                        //返回上一页面
                        setTimeout(() => {
                            uni.navigateBack({
                                delta: 1
                            });
                        }, 1000);
                    }
                })
            })
        },
        handleUploadClick() {
            this.isShow = true
        },
        // 上传图片
        async afterRead(event) {
            let lists = [].concat(event.file);
            console.log("lists", lists);
            console.log(" this[`fileList${event.name}`]",  this[`fileList${event.name}`]);
            let fileListLen = this[`fileList${event.name}`].length;
            console.log("fileListLen", fileListLen);
            lists.map((item, index) => {
                this[`fileList${event.name}`].push({
                    ...item,
                    status: "uploading",
                    message: "上传中",
                });
            });
            for (let i = 0; i < lists.length; i++) {
                const result = await this.uploadFilePromise(lists[i].url, lists, event);
                console.log("result", result);
                let item = this[`fileList${event.name}`][fileListLen];
                this[`fileList${event.name}`].splice(
                    fileListLen,
                    1,
                    Object.assign(item, {
                        status: "success",
                        message: "",
                        url: result.url,
                        name: result.fileName,
                        ossId: result.ossId
                    })
                );
                fileListLen++;
            }
        },
        uploadFilePromise(url, lists, event) {
            let token = uni.getStorageSync('token')
            let headerToken = "Bearer " + token
            return new Promise((resolve, reject) => {
                let a = uni.uploadFile({
                    url: baseUrl + "/resource/oss/upload",
                    filePath: url,
                    name: "file",
                    header: {
                        Authorization: headerToken,
                        clientId: "be7052a7e4f802c20df10a8d131adb12"
                    },
                    formData: {
                        user: "test",
                    },
                    success: (res) => {
                        let data = JSON.parse(res.data);
                        console.log("data", data);
                        if (data.code == 200) {
                            resolve(data.data);
                        } else {
                            if (lists.length > 0) {
                                lists.map((item, index) => {
                                    this[`fileList${event.name}`].splice(index, 1)
                                });
                            }
                            uni.showToast({
                                title: data.msg,
                                icon: "none",
                            });
                        }
                    },
                });
            });
        },
        // 删除图片
        deletePic(event) {
            this[`fileList${event.name}`].splice(event.index, 1);
        },
    }
}
</script>

<style scoped lang="scss">
.release {
    width: 100rpx;
    height: 70rpx;
    font-size: 28rpx;
    border-radius: 10rpx;
    background-color: #27AC2F;
    color: #ffffff;
}

// 支付弹层
.pay {
    padding: 30rpx;

    .pay-title {
        font-size: 35rpx;
    }

    .pay-select {
        margin: 50rpx;
    }

    .pay-flex {
        display: flex;
        margin-top: 30rpx;

        /deep/ .u-button {
            height: 84rpx !important;
            font-size: 30rpx;

            &:first-child {
                margin-right: 25rpx !important;
            }
        }
    }

    .surplus {
        margin-top: 35rpx;
        font-size: 25rpx;

        .surplus-num {
            margin-left: 15rpx;
        }
    }
}
</style>
